import { getUserList, getUserStats, setUserStatus, deleteUser, updateUserInfo } from '../../utils/user-api';
import Toast from 'tdesign-miniprogram/toast/index';
import auth from '../../utils/auth';

Page({
  data: {
    stats: {
      totalUsers: 0,
      activeUsers: 0,
      newUsers: 0,
      vipUsers: 0
    },
    
    keyword: '',
    userList: [],
    loading: false,
    
    pagination: {
      page: 1,
      limit: 20,
      total: 0,
      totalPages: 0
    },
    
    // 编辑弹窗
    showEditDialog: false,
    editingUser: {},
    isUpdating: false
  },

  onLoad() {
    // 检查管理员权限
    if (!this.checkAdminPermission()) {
      return;
    }
    
    this.loadStats();
    this.loadUserList();
  },

  /**
   * 检查管理员权限
   */
  checkAdminPermission() {
    if (!auth.isLoggedIn()) {
      auth.navigateToLogin('/pages/user-management/index');
      return false;
    }
    
    const userInfo = auth.getCurrentUser();
    if (!userInfo || userInfo.role !== 'admin') {
      wx.showModal({
        title: '权限不足',
        content: '只有管理员才能访问此页面',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
      return false;
    }
    
    return true;
  },

  /**
   * 加载统计信息
   */
  async loadStats() {
    try {
      const result = await getUserStats();
      if (result.success) {
        this.setData({
          stats: result.data
        });
      }
    } catch (error) {
      console.error('加载统计信息失败:', error);
    }
  },

  /**
   * 加载用户列表
   */
  async loadUserList(reset = false) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const { keyword, pagination } = this.data;
      const page = reset ? 1 : pagination.page;
      
      const result = await getUserList(page, pagination.limit, keyword);
      
      if (result.success) {
        // 格式化时间
        const userList = result.data.users.map(user => ({
          ...user,
          createTime: this.formatTime(user.createTime)
        }));
        
        this.setData({
          userList,
          pagination: {
            ...pagination,
            ...result.data.pagination
          }
        });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.message || '加载用户列表失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '网络错误，请重试',
        theme: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 搜索功能
   */
  onKeywordChange(e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  onSearch() {
    this.loadUserList(true);
  },

  /**
   * 分页功能
   */
  onPrevPage() {
    const { pagination } = this.data;
    if (pagination.page > 1) {
      this.setData({
        'pagination.page': pagination.page - 1
      });
      this.loadUserList();
    }
  },

  onNextPage() {
    const { pagination } = this.data;
    if (pagination.page < pagination.totalPages) {
      this.setData({
        'pagination.page': pagination.page + 1
      });
      this.loadUserList();
    }
  },

  /**
   * 用户编辑功能
   */
  onEditUser(e) {
    const user = e.currentTarget.dataset.user;
    this.setData({
      editingUser: { 
        ...user,
        password: '', // 密码字段默认为空
        points: user.points || 0 // 确保积分有默认值
      },
      showEditDialog: true
    });
  },

  onEditDialogChange(e) {
    this.setData({
      showEditDialog: e.detail.visible
    });
  },

  onEditUsernameChange(e) {
    this.setData({
      'editingUser.username': e.detail.value
    });
  },

  onEditNicknameChange(e) {
    this.setData({
      'editingUser.nickname': e.detail.value
    });
  },

  onEditEmailChange(e) {
    this.setData({
      'editingUser.email': e.detail.value
    });
  },

  onEditPasswordChange(e) {
    this.setData({
      'editingUser.password': e.detail.value
    });
  },

  onEditPointsChange(e) {
    const points = parseInt(e.detail.value) || 0;
    this.setData({
      'editingUser.points': points
    });
  },

  onEditStatusChange(e) {
    this.setData({
      'editingUser.status': e.detail.value
    });
  },

  onEditRoleChange(e) {
    this.setData({
      'editingUser.role': e.detail.value
    });
  },

  onCancelEdit() {
    this.setData({
      showEditDialog: false,
      editingUser: {}
    });
  },

  async onConfirmEdit() {
    if (this.data.isUpdating) return;
    
    this.setData({ isUpdating: true });
    
    try {
      const { editingUser } = this.data;
      
      // 验证邮箱格式（如果有邮箱输入）
      if (editingUser.email && !this.validateEmail(editingUser.email)) {
        throw new Error('邮箱格式不正确');
      }
      
      // 验证积分（必须是非负数）
      if (editingUser.points < 0) {
        throw new Error('积分不能为负数');
      }
      
      // 准备更新数据
      const updateData = {
        userId: editingUser.id,
        username: editingUser.username,
        nickname: editingUser.nickname,
        email: editingUser.email,
        role: editingUser.role,
        points: editingUser.points
      };
      
      // 如果有新密码，添加到更新数据中
      if (editingUser.password && editingUser.password.trim()) {
        updateData.password = editingUser.password.trim();
      }
      
      // 更新用户信息
      const updateResult = await updateUserInfo(updateData);
      
      if (!updateResult.success) {
        throw new Error(updateResult.message);
      }
      
      // 更新用户状态
      const statusResult = await setUserStatus(editingUser.id, editingUser.status);
      
      if (!statusResult.success) {
        throw new Error(statusResult.message);
      }
      
      Toast({
        context: this,
        selector: '#t-toast',
        message: '用户信息更新成功',
        theme: 'success'
      });
      
      this.setData({
        showEditDialog: false,
        editingUser: {}
      });
      
      // 重新加载列表
      this.loadUserList();
      this.loadStats();
      
    } catch (error) {
      console.error('更新用户信息失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.message || '更新失败',
        theme: 'error'
      });
    } finally {
      this.setData({ isUpdating: false });
    }
  },

  /**
   * 验证邮箱格式
   */
  validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  },

  /**
   * 用户详情
   */
  onUserTap(e) {
    const user = e.currentTarget.dataset.user;
    
    wx.showModal({
      title: '用户详情',
      content: `用户名：${user.username || '未设置'}\n昵称：${user.nickname || '未设置'}\n手机号：${user.phone || '未设置'}\n邮箱：${user.email || '未设置'}\n积分：${user.points || 0}\n角色：${this.getRoleText(user.role)}\n状态：${user.status === 'active' ? '正常' : '已禁用'}\n注册时间：${user.createTime}\n登录次数：${user.loginCount || 0}`,
      showCancel: false
    });
  },

  /**
   * 获取角色文本
   */
  getRoleText(role) {
    switch (role) {
      case 'admin':
        return '管理员';
      case 'vip':
        return 'VIP用户';
      case 'user':
      default:
        return '普通用户';
    }
  },

  /**
   * 格式化时间 - 精确到秒
   */
  formatTime(dateString) {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      return '-';
    }
  }
}); 